<?php

namespace App\ApiBackend\Role;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;


/**
 *  删除
 */
class Delete extends ApiBaseController
{
  /**
   * 参数检查
   */
  protected function check(): void
  {
    $ruleArr = [
      'id' => 'required',
    ];
    $messageArr = [
      'required' => ':attribute必须填写',
    ];
    //验证
    $validator = Validator::make(request()->all(), $ruleArr, $messageArr, [
    ]);
    //验证失败
    $errorMsg = '';
    if ($validator->stopOnFirstFailure()->fails()) {
      $errorMsg = $validator->errors()->first();
    } else {
      if (DB::table('admin')->where('adminRoleId', request('id'))->exists()) {
        $errorMsg = '请角色下有用户存在';
      }
    }
    if ($errorMsg) {
      $this->result['code'] = 1;
      $this->result['message'] = $errorMsg;
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $id = request('id');
    try {
      DB::table('admin_role')->where('id', $id)->delete();
      DB::table('admin_role_menu')->where('adminRoleId', $id)->delete();
      $this->result["message"] = '删除成功';
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
    return;
  }
}

